import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import {Table, Modal, Row, Col, Button, Tooltip, Input, Select, DatePicker} from 'antd';

import {defaultPagination, Search, TableBtn} from "../publicComponents";
import {get, post} from "../../../utils";
import {mUrl, config} from "../../../config";
import moment from "moment";
import "moment/locale/zh-cn";
import utils from "../../../utils/utils";

const { RangePicker } = DatePicker;

const Page = () => {
    const [tableData, setTableData] = useState([]); // 表格数据
    const [visible, setVisible] = useState(false);
    const [detail, setDetail] = useState({});
    const [searchDetail, setSearchDetail] = useState({});
    const [pagination, setPagination] = useState(Object.assign({},defaultPagination)); // 表格分页
    const [parentid, setParentId] = useState('');
    
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            fixed: 'left',
            align: 'center',
            width: 50,
            render: (text, record, index) => ((pagination.pageSize * (pagination.current ? pagination.current - 1 : 0)) + index + 1)
        },
        {
            title: '操作',
            align: 'center',
            fixed: 'left',
            width: 135,
            render: (text, record, index) => {
                return (
                    <TableBtn
                        onClick={handleTableBtnClick}
                        record={record}
                        btns={[
                            {id: 1, name: record.messagestate === -1 ? '上架' : '下架'},
                            {id: 2, name: '查看评论'},
                        ]}
                    />
                );
            }
        },
        {
            title: '类型',
            dataIndex: 'messagetype',
            align: 'center',
            width: 60,
            render: type => {
                const text = type === 1 ? '求购' : '需求';
                const color = type === 1 ? '#e9586e' : '#000';
                return <span style={{color}}>{text}</span>;
            }
        },
        {
            title: '有效期',
            align: 'center',
            width: 200,
            render: data => {
                if(data.createtimeshow){
                 data.messageendtime = utils.dateAddDays(data.createtimeshow,data.longtimes); 
                }
                return <span>{utils.getDate(data.createtimeshow)}至{utils.getDate(data.messageendtime)}</span>;
            }
        },
        {
            title: '是否置顶',
            dataIndex: 'istop',
            align: 'center',
            width: 80,
            render: top => {
                return top === 1 ? '是' : '否';
            }
        },
        {
            title: '付费金额/元',
            dataIndex: 'cost',
            align: 'center',
            width: 90,
        },
        {
            title: '周期/天',
            dataIndex: 'longtimes',
            align: 'center',
            width: 80,
            // render: day => day + '天'
        },
        {
            title: '状态',
            dataIndex: 'messagestate',
            align: 'center',
            width: 80,
            render: isable => isable === 1 ? '已发布' : '已下架'
        },
        {
            title: '编号',
            dataIndex: 'messageno',
            align: 'center',
            width: 100,
        },
        {
            title: '内容',
            dataIndex: 'messagecontent',
            align: 'center',
            width:150,
            render: remark => {
                let text = remark || '--';
                return (
                    <Tooltip placement={'topLeft'} title={remark}>
                        {text.length > 15 ? text.substr(0, 15) + '...' : text}
                    </Tooltip>
                );
            }  
        },
        {
            title: '地址',
            dataIndex: 'address',
            align: 'center',
            width: 150,
            render: remark => {
                let text = remark || '--';
                return (
                    <Tooltip placement={'topLeft'} title={remark}>
                        {text.length > 15 ? text.substr(0, 15) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '联系人',
            dataIndex: 'proposer',
            align: 'center',
            width: 100,
        },
        {
            title: '联系方式',
            dataIndex: 'proposerphone',
            align: 'center',
            width: 100,
        },
        {
            title: '创建时间',
            dataIndex: 'createtime',
            align: 'center',
            width: 100,
            render: create_time => utils.getDate(create_time)
        },
    ];

    useEffect(() => {
        fetch();
    }, []);

    const fetch = async (params = {}) => {
        let start = 1;
        if (params.startList > 1) {
            start = params.startList;
        }
        get(mUrl.searchMessMessageList, {pageNo: start, pageSize: pagination.pageSize, ...params}).then((res) => {
            const {list = [], count = 0} = res.data;
            pagination.total = count;
            setPagination(pagination);
            setTableData(list);
            setSearchDetail(params);
        });
    };
    
    // 上架与下架
    const handleTableBtnClick = (id, record) => {
        if (id === 1) { // 点击修改
            let text = record.messagestate === 1 ? '下架' : '上架';
            Modal.confirm({
                title: '提示',
                content: <span>是否要<span style={{color: 'red'}}>{text}</span>该信息</span>,
                onOk: () => {
                    get(mUrl.udMessage, {
                        messagestate: record.messagestate === 1 ? -1 : 1,
                        messageid: record.messageid,
                    }).then((res) => {
                        if (res.state === 1) {
                            fetch(searchDetail);
                        }
                    });
                }
            });
        } else if (id === 2) { // 点击删除
            setDetail(record);
            setVisible(true);
        }
    };

    const handleTableChange = (page) => {
        pagination.current = page.current;
        pagination.pageSize = page.pageSize;
        setPagination(pagination);
        fetch({
            startList: pagination.current
        });
    };
    
    // 搜索
    const onSearch = (value) => {
        if(value.createtime) {
            value.starttime = moment(value.createtime[0]).format('YYYY-MM-DD');
            value.endtime = moment(value.createtime[1]).format('YYYY-MM-DD');
        }
        fetch(value);
    };
    // 重置
    const onReset = () => {
        fetch();
    };
    // 导出
    const onExcel = () => {
        window.location.href = utils.getUrl(config.serverUrl + mUrl.get_exportMessMessageList, searchDetail);
    };
    

    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>消息管理 / 消息管理</p></label>
            <Search
                onSearch={onSearch}
                onReset={onReset}
                span={19}
                colNum={5}
                searchData={[
                    {
                        key: 'messagecontent', name: '内容', component: (<Input allowClear placeholder={'内容/联系人/联系方式'}/>)
                    },
                    // {
                    //     key: 'istop', name: '状态', component: (
                    //         <Select style={{width: 150}} placeholder={'请选择'}>
                    //             <Select.Option value={1}>待处理</Select.Option>
                    //             <Select.Option value={-1}>已处理</Select.Option>
                    //         </Select>
                    //     )
                    // },
                    {
                        key: 'messagetype', name: '类型', component: (
                            <Select style={{width: 120}} placeholder={'请选择'}>
                                <Select.Option value={'0'}>全部</Select.Option>
                                <Select.Option value={'1'}>求购</Select.Option>
                                <Select.Option value={'2'}>需求</Select.Option>
                            </Select>
                        )
                    },
                    {
                        key: 'messagestate', name: '状态', component: (
                            <Select style={{width: 120}} placeholder={'请选择'}>
                                <Select.Option value={'0'}>全部</Select.Option>
                                <Select.Option value={'1'}>已发布</Select.Option>
                                <Select.Option value={'-1'}>已下架</Select.Option>
                            </Select>
                        )
                    },
                    {
                        key: 'istop', name: '是否置顶', component: (
                            <Select style={{width: 120}} placeholder={'请选择'}>
                                <Select.Option value={'0'}>全部</Select.Option>
                                <Select.Option value={'1'}>是</Select.Option>
                                <Select.Option value={'-1'}>否</Select.Option>
                            </Select>)
                    },
                    {
                        key:'createtime', name:'创建时间', component:(
                            <RangePicker style={{width:230}} />
                        )
                    },
                ]}
                otherBtns={[{name: '导出', onClick: () => onExcel()}]}
            />
            <Table
                scroll={{x: 1600}}
                dataSource={tableData}
                columns={columns}
                size='small'
                bordered
                pagination={pagination}
                rowKey={"messageid"}
                onChange={handleTableChange}
                rowClassName={(record) => {
                    if (record.messageid === parentid) {
                        return 'table-select-type';
                    } else {
                        return 'table-type';
                    }
                }}
                onRow={record => {
                    return {
                        onClick: event => {
                            setParentId(record.messageid);
                        },
                    };
                }}
            />
            <MessageModal
                detail={detail}
                visible={visible}
                setVisible={setVisible}
            />
        </div>
    );
};

const MessageModal = ({visible = false, setVisible, detail}) => {
    const [messageList, setMessageList] = useState([]);
    const [count, setCount] = useState(0);
    const [pageNo, setPageNo] = useState(0);
    
    const messageItem = (list) => {
        if (list.length === 0) {
            return (
                <Col span={24}>
                    <div style={{fontSize: '16px',textAlign:'center'}}>
                        该条信息暂无评论！
                    </div>
                </Col>
            );
        }
        return list.map((item, index) => {
            if (item.createuserid === detail.createuserid) {
                return (
                    <Col key={index} span={24}>
                        <div className={'message-left-user'}>
                            <div style={{display: 'flex', flex: 1, alignItems: 'center'}}>
                                <div style={{
                                    marginRight: 15,
                                    width: 50,
                                    height: 50,
                                    borderRadius: 50,
                                    background: '#0099ff'
                                }}/>
                                <div className={'message-content'}>
                                    {
                                        item.commentstate === -1 &&
                                        <span style={{color: 'red'}}>已屏蔽</span>
                                    }
                                    <span style={{color: '#777'}}>{item.username}</span>
                                    <span style={{marginTop: 10}}>{item.content}</span>
                                </div>
                            </div>
                            <div style={{marginTop: 10}}>
                                <span>{moment(item.createtime).format('MM-DD HH:mm')}</span>
                                <br/>
                                <Button
                                    className={item.commentstate === 1 ? 'shield':''}
                                    onClick={() => updateState(item)} type={'primary'}>
                                    {item.commentstate === -1 ? '显示' : '屏蔽'}
                                </Button>
                            </div>
                        </div>
                    </Col>
                );
            } else {
                return (
                    <Col key={index} span={24}>
                        <div className={'message-right-user'}>
                            <span>{moment(item.createtime).format('MM-DD HH:mm')}</span>
                            <div className={'message-content'} style={{textAlign: 'right'}}>
                                <span>{item.username}</span>
                                <span style={{marginTop: 10}}>{item.content}</span>
                            </div>
                            <div style={{
                                marginLeft: 15,
                                width: 50,
                                height: 50,
                                borderRadius: 50,
                                background: '#0099ff'
                            }}/>
                        </div>
                    </Col>
                );
            }
        });
    };

    useEffect(() => {
        if (visible) {
            fetch1(1);
        }
    }, [visible]);

    const updateState = (data) => {
        // 1 显示 -1 隐藏
        const commentstate = data.commentstate === 1 ? -1 : 1;
        get(mUrl.udMessComment, {commentstate, commentid: data.commentid}).then((res) => {
            if (res.state === 1) {
                data.commentstate = commentstate;
                setMessageList(Object.assign([], messageList));
            }
        });
    };
    
    // 请求评论列表数据
    const fetch1 = (pageNo) => {
        get(mUrl.searchMessCommentList, {
            messageid: detail.messageid,
            // orgid:detail.orgid,
            // createuserid:detail.createuserid,
            pageNo,
            pageSize: 50
        }).then((res) => {
            if (res.state === 1) {
                setCount(res.data.count);
                setPageNo(pageNo);
                if (pageNo > 1) {
                    setMessageList(messageList.concat(res.data.list));
                } else {
                    setMessageList(res.data.list);
                }
            }
        });
    };
    
    return (
        <Modal
            width={800}
            footer={false}
            onCancel={() => setVisible(false)}
            visible={visible}
            title={'查看评论'}>
            <div style={{ backgroundColor:'#f2f2f2' }}>
                <Row>
                    {messageItem(messageList)}
                    {
                        count > messageList.length &&
                        <Button type={'primary'} onClick={() => fetch1(pageNo + 1)}>加载更多</Button>
                    }
                </Row>
                <div style={{marginTop: 10, textAlign: 'center'}}>
                    <Button 
                        style={{marginLeft: '15px'}} 
                        className={'button'}
                        onClick={_ => setVisible(false)}>
                        关闭
                    </Button>
                </div>
            </div>
        </Modal>
    );
};

export default connect()(Page);